package top.techqi.hamtools.func.diary

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.raizlabs.android.dbflow.kotlinextensions.*
import com.raizlabs.android.dbflow.rx2.kotlinextensions.rx
import com.raizlabs.android.dbflow.sql.language.BaseModelQueriable
import com.raizlabs.android.dbflow.sql.language.CursorResult
import com.raizlabs.android.dbflow.sql.language.Method
import com.raizlabs.android.dbflow.sql.language.OrderBy
import com.raizlabs.android.dbflow.sql.language.property.PropertyFactory
import com.raizlabs.android.dbflow.structure.BaseModel
import io.reactivex.Single
import kotlinx.android.synthetic.main.fragment_diary.*
import top.techqi.hamtools.R
import top.techqi.hamtools.binder.DiaryBinder
import top.techqi.hamtools.db.assist.RstR
import top.techqi.hamtools.db.assist.RstS
import top.techqi.hamtools.db.assist.RstT
import top.techqi.hamtools.db.model.DiaryModel
import top.techqi.hamtools.db.model.DiaryModel_Table.*
import top.techqi.hamtools.func.VernierFragment

class DiaryFragment : VernierFragment() {
    override val subtitle by lazy { context?.getString(R.string.fragment_diary_subtitle) }

    override fun onCreate(state: Bundle?) {
        super.onCreate(state)
        adapter.register(DiaryModel::class.java, DiaryBinder(context!!))
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_diary, container, false)
    }

    override fun onViewCreated(view: View, state: Bundle?) {
        super.onViewCreated(view, state)
        fab.setOnClickListener {
            startActivityForResult(Intent(context, DiaryEditActivity::class.java), REQUEST_ADD_NEW)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_ADD_NEW -> {
                if (resultCode == Activity.RESULT_OK) {
                    queryCursor(seacher.query.toString())
                }
            }
        }
    }

    override fun queryCursor(keyword: String): Single<out CursorResult<out BaseModel>> {
        val query: BaseModelQueriable<out DiaryModel> =
                if (keyword.isBlank()) {
                    select from DiaryModel::class orderBy
                            OrderBy.fromProperty(datetime).descending()
                } else {
                    val query = select from DiaryModel::class where
                            (sign like "%$keyword%") or
                            (mode like "%$keyword%") or
                            (freq like "%$keyword%") or
                            (power like "%$keyword%") or
                            (locate like "%$keyword%") or
                            (remote like "%$keyword%") or
                            (Method("strftime",
                                    PropertyFactory.from("%Y-%m-%d %H:%M"),
                                    datetime, PropertyFactory.from("unixepoch"),
                                    PropertyFactory.from("localtime")
                            ) like "%$keyword%")
                    if (keyword.length == 1) {
                        keyword.toIntOrNull()?.let {
                            RstR.valueOf(it).let { if (it != RstR.UNKNOWN) query or (lctR eq it) or (rmtR eq it) }
                            RstS.valueOf(it).let { if (it != RstS.UNKNOWN) query or (lctS eq it) or (rmtS eq it) }
                            RstT.valueOf(it).let { if (it != RstT.UNKNOWN) query or (lctT eq it) or (rmtT eq it) }
                        }
                    }
                    query orderBy OrderBy.fromProperty(datetime).descending()
                }

        return query.rx().queryResults()
    }

    companion object {
        const val REQUEST_ADD_NEW = 1
    }
}
